package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.util.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: Li Yu
 * @Date: 2020/11/19 19:37
 */
@Controller
@RequestMapping("/cart/")
public class CartController {
    @Reference(check = false)
    private DubboCartService dubboCartService;

    /**
     * 业务描述：展现购物车列表，同时查询购物车数据
     * url:http://www.jt.com/cart/show.html
     * 参数：userId=7
     * 返回值：页面逻辑名称 cart.jsp
     * 页面的取值：${cartList}
     */
    @RequestMapping("/show")
    public String show(Model model, HttpServletRequest request){
        User user=(User) request.getAttribute("JT_USER");
        Long userId=user.getId();
        List<Cart> cartList= dubboCartService.findCartListByUserId(userId);
        model.addAttribute("cartList", cartList);
        return "cart";
    }
    @RequestMapping("update/num/{itemId}/{num}")
    @ResponseBody   //1.数据转化为json、2.让ajax的程序结束
    public void updateCartNum(Cart cart){  //springmvc针对restFull提供的功能 名称和属性对应
        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.updateCartNum(cart);
    }

    /**
     * 实现购物车的删除操作
     * url：www.jt.com/cart/delete/商品id.html
     * @return
     */
    @RequestMapping("delete/{itemId}")
    public String deleteCart(Cart cart){
        Long userId=UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.deleteCart(cart);
        return "redirect:/cart/show.html";
    }

    /**
     * 购物车新增操作
     * 返回值：重定向到购物车页面
     */
    @RequestMapping("add/{itemId}")
    public String addCart(Cart cart){
        Long userId=UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.addCart(cart);
        return "redirect:/cart/show.html";
    }
}
